package com.zlx.mall.basic.trace;

import com.zlx.mall.basic.web.constant.TraceConstants;
import org.jetbrains.annotations.Nullable;
import org.slf4j.MDC;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author qingke
 **/
public abstract class MDCUtil {

    private static final String TRACE_KEY = TraceConstants.LOG_TRACE_ID;

    private static String generateId() {
        ThreadLocalRandom random = ThreadLocalRandom.current();
        return new UUID(random.nextLong(), random.nextLong()).toString();
    }

    @Nullable
    public static String getTraceId() {
        return MDC.get(TRACE_KEY);
    }

    public static void setTraceId(String traceId) {
        MDC.put(TRACE_KEY, traceId);
    }

    public static void clear() {
        MDC.clear();
    }

    public static String getOrCreateTraceId() {
        String traceId;
        if (StringUtils.hasText(traceId = getTraceId())) {
            return traceId;
        } else {
            setTraceId(traceId = generateId());
        }
        return traceId;
    }
}
